package com.day6.codec;

import com.day6.protocol.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 拆包器:
 * FixedLengthFrameDecoder
 * LineBasedFrameDecoder
 * DelimiterBasedFrameDecoder
 * LengthFieldBasedFrameDecoder 基于长度域的拆包器
 */
public class Spliter extends LengthFieldBasedFrameDecoder {
    private static final int LENGTH_FIELD_OFFSET = 7;//最大长度
    private static final int LENGTH_FIELD_LENGTH = 4;//长度域的偏移量
    //第三个参数是长度域的长度

    public Spliter() {
        super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        /**
         * 拒绝非本协议连接：
         *  设计魔数的原因是为了尽早屏蔽非本协议的客户端，通常在第一个 handler 处理这段逻辑
         */
        if (in.getInt(in.readerIndex()) != PacketCodeC.MAGIC_NUMBER) {
            ctx.channel().close();
            return null;
        }

        return super.decode(ctx, in);
    }
}
